import 'package:flutter/material.dart';
import 'package:flutter_manager/pages/home/index.dart';
import 'package:flutter_manager/pages/mine/index.dart';
import '../utils/TokenManager.dart';
import '../utils/Emitter.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({Key? key}) : super(key: key);

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  // 父组件定义回调函数
  void updateIndex(int index) {
    setState(() {
      activeIndex = index;
    });
  }

  List tabsList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    }
  ];
  int activeIndex = 0;

  List<BottomNavigationBarItem> getTabsBar() {
    List<BottomNavigationBarItem> list = [];
    for (var i = 0; i < tabsList.length; i++) {
      list.add(
        BottomNavigationBarItem(
            label: tabsList[i]["label"],
            icon: Image.asset(
              tabsList[i]["icon"],
              width: 30,
              height: 30,
            ),
            activeIcon: Image.asset(
              tabsList[i]["activeIcon"],
              width: 30,
              height: 30,
            )),
      );
    }
    return list;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tokenManager.init(); // 初始化token
    regiterEventBus(); // 注册监听事件
  }

  regiterEventBus() {
    eventBus.on<LogoutEvent>().listen((params) {
      // 退出登录
      Navigator.pushNamed(context, "/login");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: activeIndex,
          children: [
            const HomePage(),
            MinePage(
              currentIndex: activeIndex,
              updateIndex: updateIndex,
            )
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: activeIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        items: getTabsBar(),
        onTap: (int index) {
          setState(() {
            activeIndex = index;
          });
        },
      ),
    );
  }
}
